<template>
  <!-- 添加或修改订单产品工序分配任务对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" label-width="120px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="24">

            <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="请选择工人" prop="userId" style="width: 500px">
                <el-cascader :options="options" :props="props" v-model="regionValue"  show-all-levels clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="工作产品名称" prop="gongxuName">
                <el-input v-model="form.gongxuName" placeholder="请输入工作产品名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="工作产品型号" prop="gongxuModel">
                <el-input v-model="form.gongxuModel" placeholder="请输入工作产品型号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="单价" prop="money">
                <el-input-number v-model="form.money" placeholder="请输入单价"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="工作任务数量" prop="count">
                <el-input-number v-model="form.count" placeholder="请输入分配数量"/>
              </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-top: 30px;">
              <el-form-item label="工作任务名称" prop="name">
                <el-input v-model="form.name"  placeholder="请输入工作任务名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="图纸号" prop="shuoming">
                <el-input v-model="form.shuoming" placeholder="请输入图纸号"/>
              </el-form-item>
            </el-col>
            <el-col :span="24" style="margin-top: 30px;">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark"  placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
            <!--<el-form-item label="请购部门" prop="deptId" style="width: 500px">
              <treeselect :options="deptOptions" :show-count="true"  @select="selectDept" placeholder="请选择请购部门"
                          v-model="form.deptId"/>
            </el-form-item>
            <el-form-item label="请购人" prop="userId" style="width: 500px">
              <el-select v-model="form.userId" placeholder="请选择项目名称" filterable clearable style="width: 100%;">
                <el-option v-for="dict in userOptions" :key="dict.value"
                           :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>-->

            <!-- <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="">
                <el-button type="primary" @click="addWorker">继续添加工人</el-button>

              </el-form-item>
            </el-col> -->
          </el-row>

        </el-tab-pane>
       <!-- <el-table :data="columns" ref="dragTable" row-key="id" v-loading="loading" show-summary :summary-method="getSummaries">
          <el-table-column align="center" label="序号" type="index" width="50">
            <template slot-scope="scope">
              <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="projectNo" />
          &lt;!&ndash; <el-table-column label="工程名称" align="center" prop="gongchengName" show-overflow-tooltip />&ndash;&gt;
          <el-table-column label="产品编码" align="center" prop="goodsCode" />
          <el-table-column label="产品名称" align="center" prop="goodsName" show-overflow-tooltip />
          <el-table-column label="产品型号" align="center" prop="goodModel" />
          <el-table-column label="工艺名称" align="center" prop="gongyiName" />
          <&lt;!&ndash;el-table-column label="工序编码" align="center" prop="code" />&ndash;&gt;
          <el-table-column label="工序名称" align="center" prop="name" />
          <el-table-column label="生产名称" align="center" prop="gongxuName" show-overflow-tooltip />
          <el-table-column label="生产型号" align="center" prop="gongxuModel" />
          <el-table-column label="总数量" align="center" prop="counts" />
          <el-table-column label="已分配数量" align="center" prop="fenpeiCount" />
          &lt;!&ndash; <el-table-column label="剩余分配数量" align="center" prop="remainCount"/>&ndash;&gt;
          <el-table-column label="分配数量" width="210" prop="goodSnum">
            <template slot-scope="scope">
              <el-input-number @change="handleChange" v-model="scope.row.goodSnum" :precision="3" :min="0"
               ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="剩余分配数量" align="center" prop="remainCount" />
          <el-table-column label="已完成数量" align="center" prop="finishCount" />
          <el-table-column label="剩余完成数量" align="center" prop="remainfinishCount" />
          <el-table-column align="center" label="备注" prop="remark" />
        </el-table>-->
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitZahuo">确 定 分 配</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addAction, getById, updateAction, getAction,accAdd } from '@/api/manage';
import moment from 'moment';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect } from "@/api/system/dept";

export default {
  name: "PaigongZahuoForm",
  dicts: ['sys_user'],
  components: {
    Treeselect,
  },
  data() {
    return {
      regionValue: [],
      props: {
        multiple: true,
        emitPath: false,
        value: 'id',
        label: 'label',
        children: 'children'
      },
      options: [],
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      deptOptions: [],
      userOptions: [],
      // 是否显示弹出层
      open: false,
      parentId: null,
      counts: null,
      // 表单参数
      form: {},
      columns: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params: {},
        id: null,
        code: null,
      },
      queryParamsUser: {
        pageNum: 1,
        pageSize: 1000,
        deptId: null,
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "工人不能为空", trigger: "blur" }
        ],
        count: [
          { required: true, message: "工作任务数量不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "工作任务名称不能为空", trigger: "blur" }
        ],
      },
      url: {
        getById: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/',
        addUserTaskPiliangZahuo: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/addUserTaskPiliangZahuo',
        edit: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/edit',
        getUserByDept: '/system/user/getUserByDept',
        getAllShpper: '/system/dept/treeselect',
        getConsumer: '/system/user/getUserByDept',
        userTreeSelect: '/system/dept/userTreeSelect'
      },
      workers: [{ userId: null }], // 新增的工人选择下拉框数组
    };
  },
  created() {
    this.getTreeselect();
    this.getUser();
  },
  methods: {
     getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "counts" || column.property === "fenpeiCount" || column.property === "goodSnum" || column.property === "remainCount" || column.property === "remainfinishCount" || column.property === "finishCount") {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
    handleChange(value) {
        this.columns = JSON.parse(JSON.stringify(this.columns))
      },
    getUser() {
      let that = this;
      getAction(that.url.userTreeSelect, { parentId: '57d779853f0f4d14b03d51db30099456' }).then(res => {
        that.options = res.data;
        that.options.map((item) => {
          item = {
            value: item.id,
            label: item.label,
            children: item.children ? item.children.map(child => ({
              value: child.id,
              label: child.label
            })) : []
          }
        });
      })
    },

    selectUser(value) {
      let that = this;
      if (value && value.length > 0) {
        value.forEach((userId, index) => {
          const user = that.dict.type.sys_user.find(user => user.value === userId);
          if (user) {
            that.workers[index] = { userId: user.value, userName: user.label };
          }
        });
      } else {
        that.workers = [{ userId: null }];
      }
    },

    initUser() {
      let that = this;
      getAction(that.url.getUserByDept, this.queryParamsUser).then(res => {
        that.userOptions = res.data.nameList;
      })
    },
    selectDept(e) {
      let that = this;
      that.$set(that.form, "deptName", e.label);
      this.queryParamsUser.deptId = e.id;
      this.initUser();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    selectUser(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectUser;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.userName = arr[i].label;
          }
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xuhao: null,
        code: null,
        name: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        shuoming: null,
        status: "0",
        projectId: null,
        projectCode: null,
        projectName: null,
        saleId: null,
        goodsId: null,
        gongyiId: null,
        gongxuId: null,
        gongyiCode: null,
        goodsCode: null,
        goodsName: null,
        goodsModel: null,
        goodsBrand: null,
        doStartTime: null,
        doEndTime: null,
        planStartTime: null,
        planEndTime: null,
        userId: null,
        userName: null,
        money: null,
        count: null,
        allMoney: null,
        remainCount: null,
        parentId: null,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    paigongZahuoShow() {
      this.reset();
      /*this.columns = selectRows;
      this.columns.forEach(item => {
        item.goodSnum = item.remainCount
      });*/
      this.open = true;
      this.loading = false;
      this.title = "其他工作分配任务";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单产品工序分配任务";
      });
    },
    /** 提交按钮 */
    submitZahuo() {
      let that = this;
      let userIdres = '';
      // for (let i = 0; i < that.workers.length; i++) {
      //   if (that.workers[i].userId) {
      //     userIdres += that.workers[i].userId + ',';
      //   }
      // }
      for (let i = 0; i < that.regionValue.length; i++) {
        if (that.regionValue[i]) {
          userIdres += that.regionValue[i] + ',';
        }
      }
      if (userIdres == '') {
        that.$modal.msgError("请选择工人");
        return;
      }
      if (that.form.name == '' || that.form.name == null) {
        that.$modal.msgError("工作任务名称不能为空");
        return;
      }
      if (that.form.count == '') {
        that.$modal.msgError("工作任务数量不能为空");
        return;
      }
      const goodsOrderIn = Object.assign({});
      goodsOrderIn.userIds = userIdres;
      goodsOrderIn.gongxuName = that.form.gongxuName;
      goodsOrderIn.gongxuModel = that.form.gongxuModel;
      goodsOrderIn.money = that.form.money;
      goodsOrderIn.count = that.form.count;
      goodsOrderIn.name = that.form.name;
      goodsOrderIn.remark = that.form.remark;
      goodsOrderIn.type = '0';
      goodsOrderIn.remainCount = that.form.count;
      goodsOrderIn.shuoming = that.form.shuoming;

      addAction(that.url.addUserTaskPiliangZahuo, goodsOrderIn).then(response => {
        that.open = false;
        that.$modal.msgSuccess("选择成功！");
        that.$emit('ok');
        //that.getList2();
        that.handleQuery();
      });
      // that.$refs["form"].validate(valid => {
      //   if (valid) {

      //     const goodsOrderIn = Object.assign({});
      //     goodsOrderIn.userId = that.form.userId;
      //     goodsOrderIn.userName = that.form.userName;
      //     //goodsOrderIn.form = that.form;
      //     goodsOrderIn.columnsGongxu = that.columns;
      //     goodsOrderIn.columnsGongxu.forEach(item => {
      //       item.remainCount = item.goodSnum
      //     });
      //     addAction(that.url.addUserTaskPiliang, goodsOrderIn).then(response => {
      //       that.open = false;
      //       that.$modal.msgSuccess("选择成功！");
      //       that.$emit('ok');
      //       //that.getList2();
      //       that.handleQuery();
      //     });
      //   }
      // });

      /*this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAction(this.url.edit, this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('ok');
            });
          } else {
            addAction(this.url.addUserTask, this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit('ok');
            });
          }
        }
      });*/
    },
    addWorker() { // 新增的方法，用于动态添加工人选择下拉框
      this.workers.push({ userId: null });
    },
    deleteWorker(index) {
      this.workers.splice(index, 1);
    }
  }
};
</script>
